package com.cz.nongyetongv5.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.ListViewCheckManagerAdapter;
import com.cz.nongyetongv5.adapter.WheelViewAdapter;
import com.cz.nongyetongv5.adapter.ListViewCheckManagerAdapter.ViewHolder;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.JianChaDanWei;
import com.cz.nongyetongv5.bean.JianChaRenYuan;
import com.cz.nongyetongv5.bean.TextInfo;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.wheelview.WheelView;
import com.cz.nongyetongv5.utils.CharsetUtil;

public class ListViewCheckManagerActivity extends Activity implements
		OnClickListener, OnItemClickListener {

	/**
	 * 返回按钮
	 */
	private ViewGroup btnBack = null;

	/**
	 * 确定按钮
	 */
	private ViewGroup btnSure = null;

	/**
	 * 选择所有
	 */
	private Button btnSelectAll = null;

	/**
	 * 清除所有
	 */
	private Button btnDelete = null;

	/**
	 * 列表
	 */
	private ListView lvListView = null;

	private ListViewCheckManagerAdapter adpListView = null;

	/**
	 * 数据库帮助对象
	 */
	private DatabaseHelper db = null;

	/**
	 * 用户对象
	 */
	private User user = null;

	/**
	 * 传递过来的类型用于判断
	 */
	private String type = null;

	// 窗口标题和底部的标题
	private String title = null;

	private void initView() {
		btnBack = (ViewGroup) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);

		btnSure = (ViewGroup) findViewById(R.id.btnSure);
		btnSure.setOnClickListener(this);

		btnSelectAll = (Button) findViewById(R.id.btnSelectAll);
		btnSelectAll.setOnClickListener(this);

		btnDelete = (Button) findViewById(R.id.btnDelete);
		btnDelete.setOnClickListener(this);

		lvListView = (ListView) findViewById(R.id.lvListView);
		lvListView.setOnItemClickListener(this);

	}

	private void initConfig() {

		user = (User) getIntent().getSerializableExtra("user");

		db = new DatabaseHelper(this, CommonConstants.DBNAME, null,
				CommonConstants.DATABASE_VERSION);

		title = getIntent().getStringExtra("title");

		if (CharsetUtil.isNotNull(title)) {
			TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
			tvTitle.setText(title);
		}

		List datas = (List) getIntent().getSerializableExtra("data");

		if (datas == null) {
			datas = new ArrayList();
		}

		type = getIntent().getStringExtra("type");

		adpListView = new ListViewCheckManagerAdapter(this, datas);

		lvListView.setAdapter(adpListView);

		/*
		 * 没有数据的时候自动弹起
		 */
		if (datas.size() < 1) {
			onClick(btnSure);
		}

	}



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.listviewcheckmanager);

		initView();

		initConfig();
	}

	@Override
	public void onClick(View v) {
		if (v == btnBack) {
			doBack();
		}

		if (v == btnSure) {

			// 初始化底部弹出的窗口
			final AlertDialog bottomWindow = new AlertDialog.Builder(
					new ContextThemeWrapper(this,
							R.style.NongYeTongFullscreenTheme)).create();

			// 设置窗口的动画
			bottomWindow.getWindow().setWindowAnimations(
					R.style.bottomAnimStyle);

			// 此处可以设置dialog显示的位置 ,显示在底部
			bottomWindow.getWindow().setGravity(Gravity.BOTTOM);

			// 输入法的设置
			bottomWindow.getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
					WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

			ViewGroup bottomLayout = (ViewGroup) getLayoutInflater().inflate(
					R.layout.bottom_jianchadanwei, null);

			// 设置全屏
			bottomLayout.setMinimumWidth(getWindowManager().getDefaultDisplay()
					.getWidth());

			// 弹出对话框给他选择
			bottomWindow.show();

			bottomWindow.setContentView(bottomLayout);

			// 弹出输入法的操作
			bottomWindow.getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

			/**
			 * 加载数据滚轮
			 */
			final WheelView wvBeiJianDanWei = (WheelView) bottomLayout
					.findViewById(R.id.wvJianChaDanWei);

			final WheelViewAdapter adpWheelAdapter = new WheelViewAdapter(this);

			wvBeiJianDanWei.setAdapter(adpWheelAdapter);

			ViewGroup btnBottomBack = (ViewGroup) bottomLayout
					.findViewById(R.id.btnBack);

			btnBottomBack.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					bottomWindow.dismiss();
				}
			});

			ViewGroup btnBottomSure = (ViewGroup) bottomLayout
					.findViewById(R.id.btnSureBeiJianDanWei);

			btnBottomSure.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					TextInfo textInfo = (TextInfo) wvBeiJianDanWei
							.getSelectedItem();

					if (textInfo != null && textInfo.data != null) {
						if (!adpListView.getDatas().contains(textInfo.data)) {

							adpListView.add(textInfo.data);

							adpListView.notifyDataSetChanged();
						}
					}

					bottomWindow.dismiss();
				}
			});

			TextView tvTitle = (TextView) bottomLayout
					.findViewById(R.id.tvTitle);

			tvTitle.setText(title);

			// 检查单位根据名字进行过滤
			final EditText etBeiJianDanWeiFilter = (EditText) bottomLayout
					.findViewById(R.id.etBeiJianDanWeiFilter);

			TextWatcher textWatcher = new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
										  int before, int count) {

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
											  int count, int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {

					String filter = s.toString().trim();

					// 数据集合
					List datas = null;

					// 查询所有的检查单位信息
					if ("danwei".equals(type)) {

						if (CharsetUtil.isNotNull(filter)) {
							datas = db.queryAllJianChaDanWei(
									user.getKnowRegion() + "", filter);
							if (datas.size() < 1) {
								datas.add(new JianChaDanWei("0", filter));
							}
						} else {
							datas = db.queryAllJianChaDanWei(user
									.getKnowRegion() + "");
						}
					}

					if ("renyuan".equals(type) || "jiancharenyuan".equals(type)) {

						if (CharsetUtil.isNotNull(filter)) {
							datas = db.queryAllJianChaRenYuan(
									user.getKnowRegion() + "", filter,3);
							if (datas.size() < 1) {
								datas.add(new JianChaRenYuan("0", filter, 3));
							}
						} else {
							datas = db.queryAllJianChaRenYuanByRank(user
									.getKnowRegion() + "","3");
						}
					}

					ArrayList<TextInfo> textInfos = new ArrayList<TextInfo>();

					for (Object data : datas) {

						Object id = null;

						String name = null;

						if (data instanceof JianChaRenYuan) {

							id = ((JianChaRenYuan) data).getId();
							name = ((JianChaRenYuan) data).getName();

						}

						if (data instanceof JianChaDanWei) {
							id = ((JianChaDanWei) data).getId();
							name = ((JianChaDanWei) data).getName();
						}

						TextInfo textInfo = new TextInfo(id, name, data);

						textInfos.add(textInfo);
					}

					adpWheelAdapter.setData(textInfos);

				}
			};

			etBeiJianDanWeiFilter.addTextChangedListener(textWatcher);

			// 当开始的时候传递空的进去
			textWatcher.afterTextChanged(new SpannableStringBuilder(""));

		}

		if (v == btnSelectAll) {

			if (btnSelectAll.getText().toString().trim().equals("全选")) {

				adpListView.configCheckMap(true);

				adpListView.notifyDataSetChanged();

				btnSelectAll.setText("全不选");
			} else {

				adpListView.configCheckMap(false);

				adpListView.notifyDataSetChanged();

				btnSelectAll.setText("全选");
			}

		}

		if (v == btnDelete) {

			Map<Integer, Boolean> map = adpListView.getCheckMap();

			int count = adpListView.getCount();

			for (int i = 0; i < count; i++) {

				int position = i - (count - adpListView.getCount());

				if (map.get(i) != null && map.get(i)) {

					boolean canRemove = true;

					Object data = adpListView.getItem(position);

					if (data instanceof JianChaRenYuan) {

						canRemove = ((JianChaRenYuan) data).isAllowRemove();

					}

					if (data instanceof JianChaDanWei) {
						canRemove = ((JianChaDanWei) data).isAllowRemove();
					}

					if (canRemove) {
						adpListView.getCheckMap().remove(i);

						adpListView.remove(position);
					} else {
						map.put(position, false);
					}

				}
			}

			adpListView.notifyDataSetChanged();

		}

	}

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		if (db != null)
			db.close();

		super.onDestroy();
	}

	/**
	 * 当ListView 被点击的单机的时候
	 */
	@Override
	public void onItemClick(AdapterView<?> listView, View layout, int position,
							long arg3) {

		if (layout.getTag() instanceof ViewHolder) {

			ViewHolder holder = (ViewHolder) layout.getTag();

			holder.cbCheck.toggle();
		}

	}

	private void doBack() {

		Intent intent = new Intent();

		intent.putExtra("data", (ArrayList) adpListView.getDatas());

		intent.putExtra("type", type);

		setResult(
				ChanPinJianCeNewRecordActivity.TO_LISTVIEWCHECKMANAGER_REQUEST_CODE,
				intent);

		finish();

	}

	@Override
	public void onBackPressed() {
		doBack();
	}

}
